package com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.ImageByteUtil;
import com.css.zfzx.fwsjcj.commen.util.ImageByteUtil2;
import com.css.zfzx.fwsjcj.commen.util.ZipUtils;
import com.css.zfzx.fwsjcj.modules.structure.vo.CheckVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.entity.*;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.*;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.GeneralQueryVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.GeneralVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.SpFormVO;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.TaskFormPCQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.tools.zip.ZipOutputStream;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fw/taskForm")
@Slf4j
public class TaskFormController {

    @Autowired
    TaskFromService taskFromService;
    @Autowired
    VillagePubHouseFormService villagePubHouseFormService;
    @Autowired
    VillageHouseFormService villageHouseFormService;
    @Autowired
    NoCityTaskFromService noCityTaskFromService;
    @Autowired
    CityTaskFormService cityTaskFormService;

    /**
     * 分页查询列表    普查模块
     *
     * @param request
     * @return
     */
    @GetMapping("getPage")
    public RestResponse findPage(HttpServletRequest request, TaskFormPCQueryVo taskFormPCQueryVo) {
        RestResponse restResponse = null;
        JSONObject json = new JSONObject();
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            json = taskFromService.findPage(request, taskFormPCQueryVo, curPage, pageSize);
            json.put("message", "查询成功");
            restResponse = RestResponse.succeed(json);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查看任务相关的表单信息
     *
     * @return
     */
    @GetMapping("findById")
    public RestResponse findById(String formId, String type) {
        RestResponse restResponse = null;
        try {
            if (Constant.BULIDING_CITY.equals(type)) {
                FwCtiyHouseEntity cityById = cityTaskFormService.findCityById(formId);
                restResponse = RestResponse.succeed(cityById);
            }
            if (Constant.BULIDING_NOCITY.equals(type)) {
                FwNoctiyHouseEntity noCityById = noCityTaskFromService.findNoCityById(formId);
                restResponse = RestResponse.succeed(noCityById);
            }
            if (Constant.BULIDING_VIllAGE.equals(type)) {
                FwVillageHouseEntity villageHouseById = villageHouseFormService.findVillageHouseById(formId);
                restResponse = RestResponse.succeed(villageHouseById);
            }
            if (Constant.BULIDING_VIllAGEPUB.equals(type)) {
                FwVillagePubhouseEntity villagePubHouseById = villagePubHouseFormService.findVillagePubHouseById(formId);
                restResponse = RestResponse.succeed(villagePubHouseById);
            }
        } catch (Exception e) {
            String errormessage = "查看失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查看任务相关的所有表单信息
     *
     * @return
     */
    @GetMapping("findByType")
    public RestResponse findByType(String type) {
        RestResponse restResponse = null;
        try {
            if (Constant.BULIDING_CITY.equals(type)) {
                List<FwCtiyHouseEntity> citys = cityTaskFormService.findCitys();
                restResponse = RestResponse.succeed(citys);
            }
            if (Constant.BULIDING_NOCITY.equals(type)) {
                List<FwNoctiyHouseEntity> noCitys = noCityTaskFromService.findNoCitys();
                restResponse = RestResponse.succeed(noCitys);
            }
            if (Constant.BULIDING_VIllAGE.equals(type)) {
                List<FwVillageHouseEntity> villageHouses = villageHouseFormService.findVillageHouses();
                restResponse = RestResponse.succeed(villageHouses);
            }
            if (Constant.BULIDING_VIllAGEPUB.equals(type)) {
                List<FwVillagePubhouseEntity> villagePubHouses = villagePubHouseFormService.findVillagePubHouses();
                restResponse = RestResponse.succeed(villagePubHouses);
            }
        } catch (Exception e) {
            String errormessage = "查看失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查询所有表单
     *
     * @return
     */
    @GetMapping("queryAll")
    public RestResponse queryAll(HttpServletRequest request) {
        RestResponse restResponse = null;
        try {
            List<FwFormEntity> fwFormEntities = taskFromService.queryAll(request);
            restResponse = RestResponse.succeed(fwFormEntities);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.succeed(errormessage);
        }
        return restResponse;
    }

//    /***
//     *审核表单
//     * @return
//     */
//    @PostMapping("spForm")
//    public RestResponse spForm(@RequestBody SpFormVO spFormVO) {
//        RestResponse restResponse = null;
//        JSONObject jsonObject = new JSONObject();
//        try {
//            taskFromService.spForm(spFormVO);
//            jsonObject.put("message", "审批成功");
//            restResponse = RestResponse.succeed(jsonObject);
//        } catch (Exception e) {
//            String errormessage = "审批失败";
//            log.error(errormessage, e);
//            restResponse = RestResponse.fail(errormessage);
//        }
//        return restResponse;
//    }

    /***
     *审核表单
     * @return
     */
    @PostMapping("spForm/spCity")
    public RestResponse spFwCityForm(@RequestBody FwCtiyHouseEntity fwCtiyHouseEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.spFwCityForm(fwCtiyHouseEntity);
            jsonObject.put("message", "审批成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审批失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    @PostMapping("spForm/spNoCity")
    public RestResponse spFwNoCityForm(@RequestBody FwNoctiyHouseEntity noctiyHouseEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.spFwNoCityForm(noctiyHouseEntity);
            jsonObject.put("message", "审批成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审批失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    @PostMapping("spForm/spVillage")
    public RestResponse spFwVillageForm(@RequestBody FwVillageHouseEntity villageHouseEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.spFwVillageForm(villageHouseEntity);
            jsonObject.put("message", "审批成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审批失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    @PostMapping("spForm/spVillagePub")
    public RestResponse spFwVillagePubForm(@RequestBody FwVillagePubhouseEntity fwVillagePubhouseEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.spFwVillagePubForm(fwVillagePubhouseEntity);
            jsonObject.put("message", "审批成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审批失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 批量审批
     *
     * @param spFormVO
     * @return
     */
    @PostMapping("spAllForm")
    public RestResponse spAllForm(@RequestBody SpFormVO spFormVO) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            String ids = spFormVO.getFormId();
            String type = spFormVO.getStatus();
            String reason = spFormVO.getReason();
            taskFromService.spAllFrom(ids, type, reason);
            jsonObject.put("message", "审批成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessge = "审批不成功";
            log.error(errormessge, e);
            restResponse = RestResponse.fail(errormessge);
        }

        return restResponse;
    }

    /**
     * 逻辑删除主表并且删除子表
     *
     * @param ids
     * @return
     */
    @PostMapping("/del")
    public RestResponse delete(@RequestBody String ids) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            List<String> idList = Arrays.asList(ids.split(","));
            taskFromService.deletAll(idList);
            jsonObject.put("message", "删除成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "删除失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 导出前选中类型，判断该类型查询到的数据是否为空
     *
     * @param taskFormPCQueryVo
     * @return
     */
    @GetMapping("/isEmpty")
    public RestResponse isEmpty(TaskFormPCQueryVo taskFormPCQueryVo) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            Boolean isEmpty = taskFromService.isEmpty(taskFormPCQueryVo);
            if (isEmpty) {
                jsonObject.put("message", "是");
            } else {
                jsonObject.put("message", "否");
            }
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 导出
     *
     * @param taskFormPCQueryVo
     * @param response
     * @return
     */
    @GetMapping("/export")
    public RestResponse export(TaskFormPCQueryVo taskFormPCQueryVo, HttpServletResponse response) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.export(taskFormPCQueryVo, response);
            jsonObject.put("message", "导出成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 导入
     *
     * @param file
     * @param category
     * @return
     */
    @PostMapping("/importTask/{category}")
    public RestResponse importTask(@RequestParam("file") MultipartFile file,
                                   @RequestParam("taskName") String taskName,
                                   @RequestParam("taskId") String taskId,
                                   @PathVariable("category") String category) {
        RestResponse restResponse = null;
        try {
            long saveStart = System.currentTimeMillis();
            String result = taskFromService.importTask(file, category, taskName, taskId);
            long saveEnd = System.currentTimeMillis();
            String msg = "总耗时 " + (saveEnd - saveStart) + "毫秒" + "<br/>";
            result = msg + result;
            restResponse = RestResponse.succeed(result);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }


    /**
     * 31省-统计表格
     *
     * @param generalQueryVo
     * @return
     */
    @GetMapping("/general/provice")
    public RestResponse general(GeneralQueryVo generalQueryVo) {
        RestResponse restResponse = null;
        try {
            List<GeneralVo> generalVos = taskFromService.listGeneral(generalQueryVo);
            restResponse = RestResponse.succeed(generalVos);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 省下面的市-统计表格
     *
     * @param generalQueryVo
     * @return
     */
    @GetMapping("/general/city")
    public RestResponse cityGeneral(GeneralQueryVo generalQueryVo) {
        RestResponse restResponse = null;
        try {
            List<GeneralVo> generalVos = taskFromService.listCityGeneral(generalQueryVo);
            restResponse = RestResponse.succeed(generalVos);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 31省-总概括文字数据
     *
     * @return
     */
    @GetMapping("/general/provice/title")
    public RestResponse generalTitle() {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            GeneralVo generalTitle = taskFromService.generalTitle();
            jsonObject.put("message", "查询成功");
            jsonObject.put("data", generalTitle);
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 全国所有省的柱状图数据
     *
     * @param generalQueryVo
     * @return
     */
    @GetMapping("/general/proviceChart")
    public RestResponse proviceChart(GeneralQueryVo generalQueryVo) {
        RestResponse restResponse = null;
        try {
            JSONObject result = taskFromService.proviceChart(generalQueryVo);
            restResponse = RestResponse.succeed(result);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    @GetMapping("/general/cityChart")
    public RestResponse cityChart(GeneralQueryVo generalQueryVo) {
        RestResponse restResponse = null;
        try {
            JSONObject result = taskFromService.cityChart(generalQueryVo);
            restResponse = RestResponse.succeed(result);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 获取当前用户的Division信息
     *
     * @return
     */
    @GetMapping("/user/division")
    public RestResponse userDivision() {
        RestResponse restResponse = null;
        try {
            JSONObject result = taskFromService.userDivision();
            restResponse = RestResponse.succeed(result);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }


    /**
     * 图片打包压缩
     */
    @GetMapping(value = "/downLoadZipFile")
    public void downLoadZipFile(String type, String startDate, String endDate, String province,
                                HttpServletRequest request, HttpServletResponse response) throws IOException {
        String zipName = "图片压缩包.zip";
        zipName = URLEncoder.encode(zipName, "UTF-8");
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
        // 跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method", "POST,GET");
        // 输出流
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            // 获取图片路径
            List<String> paths = taskFromService.listImagesByType(type, startDate, endDate, province);
            // 遍历读取路径下的文件，导出为压缩包
            for (String pa : paths) {
                //File file = new File(pa);
                File file = ImageByteUtil.getFile(pa);
                if (file.exists()) {
                    System.out.println("文件名称：" + file.getName());
                    ZipUtils.doCompress(file, out);
                    response.flushBuffer();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 将base64编码转成图片格式并保存到本地，并返回虚拟路径
     *
     * @param base64Info
     * @param
     * @return
     */
    @PostMapping("/image64")
    public RestResponse image(@RequestBody String[] base64Info, String buildingCode) {

        RestResponse restResponse = null;
        try {
            List<String> imageURL = taskFromService.uploadBase64(base64Info, buildingCode);
            restResponse = RestResponse.succeed(imageURL);
        } catch (Exception e) {
            String errormessage = "上传失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;

    }

    /**
     * 根据ID获取子表信息
     *
     * @param id
     * @return
     */
    @GetMapping("getChild/{id}")
    public RestResponse getChild(@PathVariable String id) {
        RestResponse restResponse = null;
        try {
            Object object = taskFromService.getChild(id);
            restResponse = RestResponse.succeed(object);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 单独退回
     *
     * @param id
     * @param checkVo
     * @return
     */
    @PostMapping("/back/{id}")
    public RestResponse back(@PathVariable String id, @RequestBody CheckVo checkVo) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.back(id, checkVo);
            jsonObject.put("message", "退回成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "退回失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 批量退回
     *
     * @param ids
     * @param checkVo
     * @return
     */
    @PostMapping("/batchBack/{ids}")
    public RestResponse batchBack(@PathVariable String ids, @RequestBody CheckVo checkVo) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            taskFromService.batchBack(ids, checkVo);
            jsonObject.put("message", "退回成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "退回失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

}
